from flask import request, jsonify, send_file
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.api.files import files_bp
from app.services.file_service import FileService
from app.utils.response import success_response, error_response
import os
from datetime import datetime
from sqlalchemy import text
from app import db


@files_bp.route('/upload', methods=['POST'])
@jwt_required()
def upload_file():
    """
    文件上传接口
    ---
    tags:
      - 文件管理
    security:
      - Bearer: []
    consumes:
      - multipart/form-data
    parameters:
      - in: formData
        name: file
        type: file
        required: true
        description: 要上传的文件
    responses:
      200:
        description: 上传成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            message:
              type: string
              example: 上传成功
            data:
              type: object
              properties:
                id:
                  type: integer
                  example: 1
                file_name:
                  type: string
                  example: 20241205_143022_uuid.jpg
                original_name:
                  type: string
                  example: avatar.jpg
                file_url:
                  type: string
                  example: http://127.0.0.1:5000/uploads/20241205_143022_uuid.jpg
                file_size:
                  type: integer
                  example: 1024000
                file_type:
                  type: string
                  example: jpg
      400:
        description: 上传失败
    """
    try:
        # 检查文件
        if 'file' not in request.files:
            return error_response('未选择文件')
        
        file = request.files['file']
        
        # 获取当前登录用户信息（可选）
        current_user = get_jwt_identity()
        print(f"JWT身份信息原始值: {current_user}, 类型: {type(current_user)}")
        
        uploaded_by = None
        if current_user:
            if isinstance(current_user, dict):
                uploaded_by = current_user.get('id')
                print(f"从字典中获取用户ID: {uploaded_by}")
            elif isinstance(current_user, int):
                uploaded_by = current_user
                print(f"用户ID已经是整数: {uploaded_by}")
            elif isinstance(current_user, str) and current_user.isdigit():
                uploaded_by = int(current_user)
                print(f"将字符串用户ID转换为整数: {uploaded_by}")
            else:
                print(f"无法解析用户ID，原始值: {current_user}")
        
        # 设置默认值
        upload_type = 'photo'  # 默认为图片类型
        is_public = True       # 默认公开
        
        # 打印调试信息
        print(f"文件上传 - 用户ID: {uploaded_by}, 类型: {upload_type}, 是否公开: {is_public}")
        
        # 上传文件
        result = FileService.upload_file(
            file=file,
            uploaded_by=uploaded_by,
            upload_type=upload_type,
            is_public=is_public
        )
        
        if isinstance(result, dict) and 'error' in result:
            return error_response(result['error'])
        
        # 返回文件信息
        file_data = result.to_dict()
        print(f"文件上传成功 - ID: {file_data.get('id')}, 用户ID: {file_data.get('uploaded_by')}")
        
        return success_response(file_data, '上传成功')
        
    except Exception as e:
        import traceback
        print(f"文件上传异常: {str(e)}")
        print(traceback.format_exc())
        return error_response(f'上传失败: {str(e)}')


@files_bp.route('/<int:file_id>', methods=['GET'])
def get_file_info(file_id):
    """
    获取文件信息
    ---
    tags:
      - 文件管理
    parameters:
      - in: path
        name: file_id
        type: integer
        required: true
        description: 文件ID
    responses:
      200:
        description: 获取成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            message:
              type: string
              example: 获取成功
            data:
              type: object
              properties:
                id:
                  type: integer
                  example: 1
                file_name:
                  type: string
                  example: 20241205_143022_uuid.jpg
                original_name:
                  type: string
                  example: avatar.jpg
                file_url:
                  type: string
                  example: /static/uploads/20241205_143022_uuid.jpg
      404:
        description: 文件不存在
    """
    try:
        file_record = FileService.get_file_by_id(file_id)
        if not file_record:
            return error_response('文件不存在', 404)
        
        file_data = file_record.to_dict()
        file_data['file_url'] = file_record.file_url
        
        return success_response(file_data, '获取成功')
        
    except Exception as e:
        return error_response(f'获取文件信息失败: {str(e)}')


@files_bp.route('/<int:file_id>', methods=['DELETE'])
@jwt_required()
def delete_file(file_id):
    """
    删除文件
    ---
    tags:
      - 文件管理
    security:
      - Bearer: []
    parameters:
      - in: path
        name: file_id
        type: integer
        required: true
        description: 文件ID
    responses:
      200:
        description: 删除成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            message:
              type: string
              example: 删除成功
      403:
        description: 无权限删除
      404:
        description: 文件不存在
    """
    try:
        current_user = get_jwt_identity()
        user_id = None
        is_admin = False
        
        # 获取用户ID和管理员状态
        if current_user:
            if isinstance(current_user, dict):
                user_id = current_user.get('id')
                is_admin = current_user.get('role_name') == '超级管理员'
            else:
                user_id = int(current_user)
        
                # 检查是否为管理员
                from app.models.admin import Admin
                admin = Admin.query.get(user_id)
                if admin:
                    # 检查是否为超级管理员（角色ID为1或角色key包含admin）
                    is_admin = admin.role_id == 1 or (admin.role and admin.role.key == 'admin')
        
        print(f"删除文件 - 用户ID: {user_id}, 是否管理员: {is_admin}, 文件ID: {file_id}")
        
        # 检查文件是否存在
        file_record = FileService.get_file_by_id(file_id)
        if not file_record:
            return error_response('文件不存在', 404)
        
        # 权限检查：如果是管理员或文件所有者，允许删除
        if is_admin or file_record.upload_user_id == user_id:
            result = FileService.delete_file(file_id)
            
            if not result:
                return error_response('删除失败', 500)
            
            return success_response(None, '删除成功')
        else:
            return error_response('无权限删除此文件', 403)
        
    except Exception as e:
        import traceback
        print(f"删除文件异常: {str(e)}")
        print(traceback.format_exc())
        return error_response(f'删除失败: {str(e)}')


@files_bp.route('/my', methods=['GET'])
@jwt_required()
def get_my_files():
    """
    获取我的文件列表
    ---
    tags:
      - 文件管理
    security:
      - Bearer: []
    parameters:
      - in: query
        name: usage_type
        type: string
        required: false
        description: 使用类型过滤
      - in: query
        name: page
        type: integer
        required: false
        description: 页码
        default: 1
      - in: query
        name: per_page
        type: integer
        required: false
        description: 每页数量
        default: 20
    responses:
      200:
        description: 获取成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            message:
              type: string
              example: 获取成功
            data:
              type: object
              properties:
                items:
                  type: array
                  items:
                    type: object
                    properties:
                      id:
                        type: integer
                      file_name:
                        type: string
                      original_name:
                        type: string
                      file_url:
                        type: string
                total:
                  type: integer
                pages:
                  type: integer
                page:
                  type: integer
                per_page:
                  type: integer
    """
    try:
        # 获取当前用户ID
        current_user = get_jwt_identity()
        print(f"JWT身份信息: {current_user}, 类型: {type(current_user)}")
        
        user_id = None
        if isinstance(current_user, dict):
            user_id = current_user.get('id')
        elif isinstance(current_user, int):
            user_id = current_user
        elif isinstance(current_user, str):
            try:
                user_id = int(current_user)
                print(f"将字符串用户ID转换为整数: {user_id}")
            except ValueError:
                print(f"无法将字符串转换为整数: {current_user}")
        else:
            print(f"无法解析用户ID，原始值: {current_user}")
        
        if not user_id:
            return error_response('无法识别当前用户，请重新登录', 401)
        
        # 获取查询参数    
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 20))
        file_type = request.args.get('file_type', '')
        upload_type = request.args.get('upload_type', '')
        keyword = request.args.get('keyword', '')
        
        print(f"准备查询文件列表 - 用户ID: {user_id}, 页码: {page}, 限制: {limit}")
        
        # 直接查询数据库，检查是否有该用户的文件
        from app import db
        from app.models.file_upload import FileUpload
        from sqlalchemy import text
        
        sql = text("SELECT COUNT(*) FROM file_uploads WHERE upload_user_id = :user_id AND status = 1")
        count = db.session.execute(sql, {'user_id': user_id}).scalar()
        print(f"直接SQL查询结果: 用户ID {user_id} 有 {count} 个文件")
        
        # 获取所有文件记录，检查是否有问题
        if count == 0:
            all_files = FileUpload.query.filter_by(status=1).all()
            print(f"系统中共有 {len(all_files)} 个文件")
            for file in all_files[:5]:  # 只打印前5个文件信息
                print(f"文件ID: {file.id}, 用户ID: {file.upload_user_id}, 文件名: {file.file_name}")
        
        result = FileService.get_files_by_user(
            user_id=user_id,
            page=page,
            limit=limit,
            file_type=file_type,
            upload_type=upload_type,
            keyword=keyword
        )
        
        print(f"查询结果 - 总数: {result.get('total', 0)}")
        
        return success_response(result, '获取成功')
        
    except Exception as e:
        import traceback
        print(f"获取文件列表失败: {str(e)}")
        print(traceback.format_exc())
        return error_response(f'获取文件列表失败: {str(e)}')


@files_bp.route('/public', methods=['GET'])
def get_public_files():
    """
    获取公开文件列表
    ---
    tags:
      - 文件管理
    parameters:
      - in: query
        name: file_type
        type: string
        required: false
        description: 文件类型过滤
      - in: query
        name: upload_type
        type: string
        required: false
        description: 上传类型过滤
      - in: query
        name: keyword
        type: string
        required: false
        description: 关键词搜索
      - in: query
        name: page
        type: integer
        required: false
        description: 页码
        default: 1
      - in: query
        name: limit
        type: integer
        required: false
        description: 每页数量
        default: 20
    responses:
      200:
        description: 获取成功
    """
    try:
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 20))
        file_type = request.args.get('file_type', '')
        upload_type = request.args.get('upload_type', '')
        keyword = request.args.get('keyword', '')
        
        result = FileService.get_public_files(
            page=page,
            limit=limit,
            file_type=file_type,
            upload_type=upload_type,
            keyword=keyword
        )
        
        return success_response(result, '获取成功')
        
    except Exception as e:
        return error_response(f'获取公开文件列表失败: {str(e)}')


@files_bp.route('/download/<int:file_id>', methods=['GET'])
def download_file(file_id):
    """
    下载文件
    ---
    tags:
      - 文件管理
    parameters:
      - in: path
        name: file_id
        type: integer
        required: true
        description: 文件ID
    responses:
      200:
        description: 下载成功
      404:
        description: 文件不存在
    """
    try:
        file_record = FileService.get_file_by_id(file_id)
        if not file_record:
            return error_response('文件不存在', 404)
        
        if not os.path.exists(file_record.file_path):
            return error_response('文件不存在', 404)
        
        return send_file(
            file_record.file_path,
            as_attachment=True,
            download_name=file_record.original_name
        )
        
    except Exception as e:
        return error_response(f'下载文件失败: {str(e)}') 


@files_bp.route('/debug', methods=['GET'])
@jwt_required()
def debug_files():
    """
    调试文件接口 - 仅供开发使用
    """
    try:
        current_user = get_jwt_identity()
        user_id = None
        if current_user:
            if isinstance(current_user, dict):
                user_id = current_user.get('id')
            else:
                user_id = int(current_user)
                
        # 检查数据库中的文件记录
        result = []
        
        # 1. 直接查询原始SQL
        sql = text("SELECT * FROM file_uploads WHERE upload_user_id = :user_id AND status = 1")
        raw_rows = db.session.execute(sql, {'user_id': user_id}).fetchall()
        
        # 将原始结果转换为字典
        for row in raw_rows:
            # 将每一列转换为字典
            row_dict = {}
            for column, value in row._mapping.items():
                if value is not None:
                    if isinstance(value, datetime):
                        row_dict[column] = value.strftime('%Y-%m-%d %H:%M:%S')
                    else:
                        row_dict[column] = str(value)
                else:
                    row_dict[column] = None
            result.append(row_dict)
        
        # 2. 使用ORM查询
        from app.models.file_upload import FileUpload
        orm_files = FileUpload.query.filter_by(upload_user_id=user_id, status=1).all()
        orm_result = [
            {
                'id': file.id,
                'file_name': file.file_name,
                'original_name': file.original_name,
                'upload_user_id': file.upload_user_id,
                'created_at': file.created_at.strftime('%Y-%m-%d %H:%M:%S') if file.created_at else None
            }
            for file in orm_files
        ]
        
        return {
            'user_id': user_id,
            'raw_count': len(raw_rows),
            'orm_count': len(orm_files),
            'raw_results': result,
            'orm_results': orm_result
        }
        
    except Exception as e:
        return error_response(f'调试失败: {str(e)}')


@files_bp.route('/admin/list', methods=['GET'])
@jwt_required()
def get_admin_files():
    """
    获取所有文件列表（管理员专用）
    ---
    tags:
      - 文件管理
    security:
      - Bearer: []
    parameters:
      - in: query
        name: file_type
        type: string
        required: false
        description: 文件类型过滤
      - in: query
        name: keyword
        type: string
        required: false
        description: 关键词搜索
      - in: query
        name: page
        type: integer
        required: false
        description: 页码
        default: 1
      - in: query
        name: limit
        type: integer
        required: false
        description: 每页数量
        default: 20
    responses:
      200:
        description: 获取成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            message:
              type: string
              example: 获取成功
            data:
              type: object
              properties:
                items:
                  type: array
                  items:
                    type: object
                    properties:
                      id:
                        type: integer
                      file_name:
                        type: string
                      original_name:
                        type: string
                      file_url:
                        type: string
                total:
                  type: integer
                pages:
                  type: integer
                page:
                  type: integer
                limit:
                  type: integer
    """
    try:
        # 验证是否是管理员（此处可根据实际情况添加权限验证）
        current_user = get_jwt_identity()
        
        # 获取查询参数    
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 20))
        file_type = request.args.get('file_type', '')
        keyword = request.args.get('keyword', '')
        
        print(f"管理员查询所有文件 - 页码: {page}, 限制: {limit}")
        
        # 获取所有文件，不区分上传用户
        result = FileService.get_all_files(
            page=page,
            limit=limit,
            file_type=file_type,
            keyword=keyword
        )
        
        print(f"查询结果 - 总数: {result.get('total', 0)}")
        
        return success_response(result, '获取成功')
        
    except Exception as e:
        import traceback
        print(f"获取文件列表失败: {str(e)}")
        print(traceback.format_exc())
        return error_response(f'获取文件列表失败: {str(e)}')


@files_bp.route('/check-auth', methods=['GET'])
@jwt_required()
def check_auth():
    """
    检查当前用户的认证信息（调试用）
    ---
    tags:
      - 文件管理
    security:
      - Bearer: []
    responses:
      200:
        description: 获取成功
    """
    try:
        # 获取JWT身份信息
        current_user = get_jwt_identity()
        print(f"JWT身份信息: {current_user}, 类型: {type(current_user)}")
        
        # 获取用户详细信息
        user_info = None
        is_admin = False
        
        if current_user:
            if isinstance(current_user, dict):
                user_id = current_user.get('id')
                is_admin = current_user.get('role_name') == '超级管理员'
                user_info = current_user
            else:
                try:
                    user_id = int(current_user)
                    # 查询管理员信息
                    from app.models.admin import Admin
                    admin = Admin.query.get(user_id)
                    if admin:
                        user_info = admin.to_dict()
                        is_admin = admin.role_id == 1 or (admin.role and admin.role.key == 'admin')
                except Exception as e:
                    print(f"获取用户信息失败: {str(e)}")
        
        # 获取JWT声明
        from flask_jwt_extended import get_jwt
        jwt_claims = get_jwt()
        
        return success_response({
            'identity': current_user,
            'user_info': user_info,
            'is_admin': is_admin,
            'jwt_claims': jwt_claims
        }, '获取成功')
        
    except Exception as e:
        import traceback
        print(f"检查认证信息失败: {str(e)}")
        print(traceback.format_exc())
        return error_response(f'检查认证信息失败: {str(e)}') 